package com.sxhalo.fsms.task;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import com.sxhalo.fsms.domain.MotorReliabilityData;
import com.sxhalo.fsms.domain.RedisData;
import com.sxhalo.fsms.service.FactDeviceService;
import com.sxhalo.fsms.service.MotorReliabilityDataService;
import com.sxhalo.fsms.service.MotorRunningDataService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.websocket.Session;

/**
 * 任务 01
 */

public class ScheduledTask01 implements ScheduledTaskJob {
	/**
	 * 日志
	 */
	private static final Logger LOGGER = LoggerFactory.getLogger(ScheduledTask01.class);

	@Autowired
	private FactDeviceService deviceService;
	@Autowired
	private MotorReliabilityDataService reliabilityDataService;
	@Autowired
	private MotorRunningDataService runningDataService;

	private ObjectMapper oMapper = new ObjectMapper();

	public ScheduledTask01() {
		// new的时候注入需要的bean
		// this.deviceService = SpringContextUtil.getBean(FactDeviceService.class);
	}


	@Override
	public void run() {
		if (this.deviceService == null) {
			this.deviceService = SpringContextUtil.getBean(FactDeviceService.class);
			this.reliabilityDataService = SpringContextUtil.getBean(MotorReliabilityDataService.class);
			this.runningDataService = SpringContextUtil.getBean(MotorRunningDataService.class);
		}
		Date nowTime = new Date();
		List<Integer> deviceIds = deviceService.getAllId(" use_state=1 ");
		List<RedisData> redisDataList = new ArrayList<RedisData>();
		List<MotorReliabilityData> updateList = new ArrayList<MotorReliabilityData>();
		List<MotorReliabilityData> saveList = new ArrayList<MotorReliabilityData>();

		MotorReliabilityData newReliabilityData;
		MotorReliabilityData oldReliabilityData;

		RedisData source = null;
		Boolean isLast = false;
		Integer id;
		for (int i = 0; i < deviceIds.size(); i++) {
			id = deviceIds.get(i);
			Map<Object, Object> map = deviceService.getLiveData(id.toString());
			source = JSON.parseObject(JSON.toJSONString(map), RedisData.class);
			if (source != null) {
				source.setDeviceId(id);
				source.setAcquisitionTime(nowTime);
				redisDataList.add(source);
				oldReliabilityData = reliabilityDataService.selectByPrimaryKey(id);
				newReliabilityData = new MotorReliabilityData();
				newReliabilityData.setDeviceId(id);
				newReliabilityData.setAcquisitionTime(nowTime);
				newReliabilityData.setTotalStart(source.getTotalStart());
				newReliabilityData.setTotalTrip(source.getTotalTrip());
				newReliabilityData.setTotalRuningHour(source.getTotalRuningHour());
				newReliabilityData.setCurrentRuningHour(source.getCurrentRuningHour());
				if (oldReliabilityData == null) {
					saveList.add(newReliabilityData);
				}
				if (oldReliabilityData != null && !md5CheckSum(oldReliabilityData, newReliabilityData)) {
					newReliabilityData.setAcquisitionTime(nowTime);
					updateList.add(newReliabilityData);
				}
			}
			if (i == deviceIds.size() - 1) {
				isLast = true;
			}
			toSave(redisDataList, updateList, saveList, isLast);

		}

		sendLiveData();

		LOGGER.info("ScheduledTask => 01  run  当前线程名称 {} ", Thread.currentThread().getName());

	}

	private void toSave(List<RedisData> redisDataList, List<MotorReliabilityData> updateList,
			List<MotorReliabilityData> saveList, Boolean isLast) {
		if (redisDataList.size() >= 200) {
			runningDataService.batchSave(redisDataList);
			redisDataList.clear();
		}

		if (updateList.size() >= 200) {
			reliabilityDataService.batchUpdate(updateList);
			updateList.clear();
		}

		if (saveList.size() >= 200) {
			reliabilityDataService.batchSave(saveList);
			saveList.clear();
		}
		if (isLast) {
			if (redisDataList.size() > 0) {
				runningDataService.batchSave(redisDataList);
			}
			if (updateList.size() > 0) {
				reliabilityDataService.batchUpdate(updateList);
			}
			if (saveList.size() > 0) {
				reliabilityDataService.batchSave(saveList);
			}

		}
	}

	private boolean md5CheckSum(MotorReliabilityData old, MotorReliabilityData now) {
		old.setAcquisitionTime(null);
		now.setAcquisitionTime(null);
		try {
			String a = oMapper.writeValueAsString(old);
			String b = oMapper.writeValueAsString(now);
			return a.equals(b);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		return false;
	}
	
	private void sendLiveData() {
		Map<String, Session> map = WebSocketServer.getMapSe();
		Map<String, String> ids = WebSocketServer.getMapId();
		for (Map.Entry<String, Session> entry : map.entrySet()) {
		    String key = entry.getKey();
		    Session session = entry.getValue();
		    Map<Object, Object> temp = deviceService.getLiveData(ids.get(key));
		    String json = "";
			try {
				json = oMapper.writeValueAsString(temp);
			} catch (JsonProcessingException e) {
				e.printStackTrace();
			}
			if(session.isOpen()) {
				WebSocketServer.sendMessage(json, session);
				System.out.println(key);
			}
		}
	}

}
